const multer = require('@koa/multer');
const COS = require('cos-nodejs-sdk-v5');
const account = require('@/config/Account')
//上传图片到服务器端
const storage = multer.diskStorage({
    filename:(req,file,cb)=>{
        // console.log(file);
        let fileFormat = (file.originalname).split(".")
        let newCode = `${new Date().getTime()}${'.'}${fileFormat[fileFormat.length-1]}`
        cb(null,newCode)
    }
})

const upload = multer({storage});
const cos = new COS({
    SecretId: account.COS_SECRETID,
    SecretKey: account.COS_SECRETKEY,
    FileParallelLimit:6,
    ChunkParallelLimit:6,
    Protocol:'https',
    UseAccelerate:true
})

//上传到腾讯云
const cosUpdate = async (value) => {
    const bucket = account.COS_BUCKET;
    const region = account.COS_REGION;
    const folder = account.COS_FOLDER;

    const results = [];
    for (const item of value) {
        const params = {
            Bucket: bucket,
            Region: region,
            Key: `${folder}${item.filename}`,
            FilePath: item.path,
        };

        try {
            const data = await cos.uploadFile(params);
            const res = `https://${data.Location}`;
            // console.log(res);
            results.push(res);
        } catch (err) {
            // console.error(err);
            throw err;
        }
    }

    return results;
};



module.exports = {upload,cosUpdate}